//TODO
package org.dyndns.cooland.updater.util;

import java.io.*;
import java.util.*;

public class INIFile {

	/**
	 * We will use Properties class for storing our settings
	 */
	private Properties iniProperty = new Properties();
	/**
	 * INI file name for internal use
	 */
	private String fileName;
	
	
	
	public INIFile(String fname) throws IOException{
		fileName = fname;
		loadFile(fname);
	}
	
	public boolean createFile() throws IOException{
		return createFile(fileName);
	}
	
	public boolean createFile(String file) throws IOException{
		File f = new File(file);
		return	f.createNewFile();
	}
	
	private void loadFile( String fname ) throws IOException
	 {
	  BufferedReader br = new BufferedReader(
	   new InputStreamReader(new FileInputStream(fname)));

	  try
	  {
	   String section = "";
	   String line;

	   while( (line = br.readLine())!=null )
	   {
	    if( line.startsWith(";")||line.startsWith("#") ) continue;
	    if( line.startsWith("[") )
	    {
	     section = line.substring(1,line.lastIndexOf("]")).trim();
	     continue;
	    }
	    addProperty(section,line);
	   }
	  }
	  finally { br.close(); }
	 }
	
	
	private String removeComments(String line){
		int index1 = line.indexOf(";");
		if (index1>-1){
			line = line.substring(0,index1).trim();
		}
		int index2 = line.indexOf("#");
		if (index2>-1){
			line = line.substring(0, index2).trim();
		}
		return line;
	}
	
	private void addProperty(String section,String line)
	 {
		line = removeComments(line);
	  int equalIndex = line.indexOf("=");

	  if( equalIndex > 0 )
	  {
	   String name = section+'.'+line.substring(0,equalIndex).trim();
	   String value = line.substring(equalIndex+1).trim();
	   iniProperty.put(name,value);
	  }
	 }

	 public String getProperty(String section,String var,String def)
	 {
	  return iniProperty.getProperty(section+'.'+var,def);
	 }

	 public int getProperty(String section,String var,int def)
	 {
	  String sval = getProperty(section,var,Integer.toString(def));
	  
	  return Integer.decode(sval).intValue();
	 }

	 public boolean getProperty(String section,String var,boolean def)
	 {
	  String sval = getProperty(section,var,def ? "True":"False");

	  return sval.equalsIgnoreCase("Yes") || 
	           sval.equalsIgnoreCase("True");
	 }
}
